<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>Spring Boot + Spring Security + OAuth2 + JWT + Redis：构建安全的身份认证与授权解决方案集成 | 坤个人博客</title><meta name="author" content="Houkl"><meta name="copyright" content="Houkl"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="引言：今天我们将一起深入探讨Spring Security与OAuth2、JWT以及Redis的结合使用，构建一个强大而安全的身份认证和授权解决方案。在本篇博客中，我将详细介绍Spring Security + OAuth2 + JWT + Redis的功能和原理，并附上一些代码示例，帮助你更好地理解和应用这些技术。 1. 功能介绍 Spring Security： 认证（Authenticati">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring Boot + Spring Security + OAuth2 + JWT + Redis：构建安全的身份认证与授权解决方案集成">
<meta property="og:url" content="http://hkl.gitee.io/houkl/2018/08/16/srping/SpringSecurityOAuth2JWTRedis/index.html">
<meta property="og:site_name" content="坤个人博客">
<meta property="og:description" content="引言：今天我们将一起深入探讨Spring Security与OAuth2、JWT以及Redis的结合使用，构建一个强大而安全的身份认证和授权解决方案。在本篇博客中，我将详细介绍Spring Security + OAuth2 + JWT + Redis的功能和原理，并附上一些代码示例，帮助你更好地理解和应用这些技术。 1. 功能介绍 Spring Security： 认证（Authenticati">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://s1.ax1x.com/2023/06/05/pCCUheP.png">
<meta property="article:published_time" content="2018-08-15T16:00:00.000Z">
<meta property="article:modified_time" content="2018-08-15T16:00:00.000Z">
<meta property="article:author" content="Houkl">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://s1.ax1x.com/2023/06/05/pCCUheP.png"><link rel="shortcut icon" href="/houkl/img/favicon.png"><link rel="canonical" href="http://hkl.gitee.io/houkl/2018/08/16/srping/SpringSecurityOAuth2JWTRedis/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/houkl/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/houkl/',
  algolia: undefined,
  localSearch: {"path":"/houkl/search.xml","preload":false,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Spring Boot + Spring Security + OAuth2 + JWT + Redis：构建安全的身份认证与授权解决方案集成',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2018-08-16 00:00:00'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = 'hidden';
    document.getElementById('loading-box').classList.remove("loaded")
  }
}

preloader.initLoading()
window.addEventListener('load',()=> { preloader.endLoading() })

if (false) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://s1.ax1x.com/2023/05/31/p9v6spQ.md.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/houkl/archives/"><div class="headline">文章</div><div class="length-num">21</div></a><a href="/houkl/tags/"><div class="headline">标签</div><div class="length-num">0</div></a><a href="/houkl/categories/"><div class="headline">分类</div><div class="length-num">8</div></a></div><hr/></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://s1.ax1x.com/2023/06/05/pCCUheP.png')"><nav id="nav"><span id="blog-info"><a href="/houkl/" title="坤个人博客"><span class="site-name">坤个人博客</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Spring Boot + Spring Security + OAuth2 + JWT + Redis：构建安全的身份认证与授权解决方案集成</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2018-08-15T16:00:00.000Z" title="发表于 2018-08-16 00:00:00">2018-08-16</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2018-08-15T16:00:00.000Z" title="更新于 2018-08-16 00:00:00">2018-08-16</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/houkl/categories/spring%E7%A8%8B%E5%BA%8F%E5%91%98%E7%9A%84%E6%98%A5%E5%A4%A9/">spring程序员的春天</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Spring Boot + Spring Security + OAuth2 + JWT + Redis：构建安全的身份认证与授权解决方案集成"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p>引言：<br>今天我们将一起深入探讨Spring Security与OAuth2、JWT以及Redis的结合使用，构建一个强大而安全的身份认证和授权解决方案。在本篇博客中，我将详细介绍Spring Security + OAuth2 + JWT + Redis的功能和原理，并附上一些代码示例，帮助你更好地理解和应用这些技术。</p>
<h2 id="1-功能介绍-Spring-Security："><a href="#1-功能介绍-Spring-Security：" class="headerlink" title="1. 功能介绍 Spring Security："></a>1. 功能介绍 Spring Security：</h2><ul>
<li>认证（Authentication）：验证用户的身份信息，并确保用户是可信的。</li>
<li>授权（Authorization）：授予用户访问资源的权限，限制用户对受保护资源的操作。</li>
<li>攻击防护（Attack Protection）：提供防止常见攻击的机制，如跨站点请求伪造（CSRF）和跨站脚本攻击（XSS）。</li>
<li>会话管理（Session Management）：管理用户的会话，并提供注销、超时和并发会话控制等功能。</li>
<li>加密（Encryption）：提供加密算法和工具，保护用户的敏感信息。</li>
</ul>
<ol>
<li>原理解析 Spring Security的核心原理是基于过滤器链（Filter Chain）的。在Web应用程序中，每个请求都会经过一系列的过滤器，用于完成不同的安全功能。Spring Security利用了Servlet规范中的Filter机制，将安全相关的逻辑集成到过滤器链中。</li>
</ol>
<p>过滤器链的顶端是一个特殊的过滤器：<code>DelegatingFilterProxy</code>。它会将请求转发给实际的Spring Security过滤器链，这些过滤器负责执行不同的安全任务，如认证、授权、攻击防护等。每个过滤器都有特定的职责，它们协同工作以实现完整的安全功能。</p>
<p>Spring Security还与认证提供者（Authentication Provider）密切相关。认证提供者负责验证用户的身份信息，并生成相应的认证凭证（Authentication Credentials）。这些凭证将在整个过滤器链中传递，用于进行授权和会话管理等操作。</p>
<h3 id="2-1-示例代码-现在，让我们通过一个简单的代码示例来演示Spring-Security的使用："><a href="#2-1-示例代码-现在，让我们通过一个简单的代码示例来演示Spring-Security的使用：" class="headerlink" title="2.1. 示例代码 现在，让我们通过一个简单的代码示例来演示Spring Security的使用："></a>2.1. 示例代码 现在，让我们通过一个简单的代码示例来演示Spring Security的使用：</h3><p>首先，我们需要配置Spring Security的过滤器链。可以通过XML配置或Java配置来实现。下面是一个使用Java配置的示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@EnableWebSecurity</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SecurityConfig</span> <span class="keyword">extends</span> <span class="title class_">WebSecurityConfigurerAdapter</span> &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(HttpSecurity http)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        http</span><br><span class="line">            .authorizeRequests()</span><br><span class="line">                .antMatchers(<span class="string">&quot;/public&quot;</span>).permitAll()</span><br><span class="line">                .anyRequest().authenticated()</span><br><span class="line">                .and()</span><br><span class="line">            .formLogin()</span><br><span class="line">                .loginPage(<span class="string">&quot;/login&quot;</span>)</span><br><span class="line">                .permitAll()</span><br><span class="line">                .and()</span><br><span class="line">            .logout()</span><br><span class="line">                .logoutUrl(<span class="string">&quot;/logout&quot;</span>)</span><br><span class="line">                .permitAll();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>在上面的配置中，我们定义了访问规则，指定了哪些URL需要进行认证，哪些URL可以匿名访问。我们还配置了登录页面和注销URL。</p>
<p>接下来，我们可以定义自定义的认证提供者和用户详细信息服务，以验证用户的身份信息和加载用户的权限信息。例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">CustomUserDetailsService</span> <span class="keyword">implements</span> <span class="title class_">UserDetailsService</span> &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> UserDetails <span class="title function_">loadUserByUsername</span><span class="params">(String username)</span> <span class="keyword">throws</span> UsernameNotFoundException &#123;</span><br><span class="line">        <span class="comment">// 根据用户名从数据库加载用户信息</span></span><br><span class="line">        <span class="comment">// 返回UserDetails对象，包含用户名、密码和权限等信息</span></span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>最后，我们可以在应用程序中使用Spring Security的注解来实现更精细的授权控制。例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MyController</span> &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@GetMapping(&quot;/admin&quot;)</span></span><br><span class="line">    <span class="meta">@PreAuthorize(&quot;hasRole(&#x27;ROLE_ADMIN&#x27;)&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">adminPage</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">// 只有具备ROLE_ADMIN角色的用户才能访问该页面</span></span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="2-OAuth2：使用、原理"><a href="#2-OAuth2：使用、原理" class="headerlink" title="2.OAuth2：使用、原理"></a>2.OAuth2：使用、原理</h2><p>OAuth是一种用于授权和身份验证的开放标准，它允许用户在不透露他们的凭证（用户名和密码）的情况下，授权第三方应用程序访问他们的受保护资源。在本篇博客中，我们将介绍OAuth的基本概念、工作原理，并提供一个简单的示例代码来演示如何使用OAuth进行授权和访问受保护的资源。</p>
<h3 id="2-1-OAuth2基本概念"><a href="#2-1-OAuth2基本概念" class="headerlink" title="2.1.OAuth2基本概念"></a>2.1.OAuth2基本概念</h3><ul>
<li><p><strong>资源所有者（Resource Owner）</strong>: 资源所有者是指那些拥有受保护资源的用户。例如，一个用户拥有的照片存储在某个照片共享网站上。</p>
</li>
<li><p><strong>客户端（Client）</strong>: 客户端是指第三方应用程序，它希望获得资源所有者的授权来访问受保护资源。例如，一个照片编辑应用程序希望获取用户照片的访问权限。</p>
</li>
<li><p><strong>授权服务器（Authorization Server）</strong>: 授权服务器负责验证资源所有者的身份，并颁发访问令牌给客户端。它允许客户端通过合适的授权流程来获取访问令牌。</p>
</li>
<li><p><strong>资源服务器（Resource Server）</strong>: 资源服务器存储和提供受保护的资源。它会验证访问令牌，并根据令牌的权限来决定是否允许客户端访问资源。</p>
</li>
</ul>
<h3 id="2-2-OAuth2-工作原理"><a href="#2-2-OAuth2-工作原理" class="headerlink" title="2.2. OAuth2 工作原理"></a>2.2. OAuth2 工作原理</h3><ol>
<li><p>客户端向授权服务器发起授权请求，请求包括客户端标识和重定向URI。</p>
</li>
<li><p>授权服务器验证资源所有者的身份，并要求资源所有者授权给客户端访问受保护资源。</p>
</li>
<li><p>如果资源所有者同意授权，授权服务器将发起一个重定向，将授权码（Authorization Code）传递给客户端。</p>
</li>
<li><p>客户端使用授权码向授权服务器请求访问令牌（Access Token）。</p>
</li>
<li><p>授权服务器验证授权码，并颁发访问令牌给客户端。</p>
</li>
<li><p>客户端使用访问令牌向资源服务器请求访问受保护的资源。</p>
</li>
<li><p>资源服务器验证访问令牌，并根据令牌的权限来决定是否授权客户端访问资源。</p>
</li>
</ol>
<h3 id="2-3-OAuth2示例代码"><a href="#2-3-OAuth2示例代码" class="headerlink" title="2.3. OAuth2示例代码"></a>2.3. OAuth2示例代码</h3><p>以下是一个使用Spring Boot和Spring Security实现基于OAuth 2.0的简单示例代码。该示例使用GitHub作为授权服务器和资源服务器。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@EnableWebSecurity</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SecurityConfig</span> <span class="keyword">extends</span> <span class="title class_">WebSecurityConfigurerAdapter</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(HttpSecurity http)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        http</span><br><span class="line">            .authorizeRequests()</span><br><span class="line">                .antMatchers(<span class="string">&quot;/&quot;</span>, <span class="string">&quot;/login**&quot;</span>)</span><br><span class="line">                .permitAll()</span><br><span class="line">                .anyRequest()</span><br><span class="line">                .authenticated()</span><br><span class="line">                .and()</span><br><span class="line">            .oauth2Login();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OAuth2ExampleApplication</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        SpringApplication.run(OAuth2ExampleApplication.class, args);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>上述代码配置了基本的Spring Security，允许任何人访问根路径和登录页面。在登录时，它将重定向到进行身份验证，并颁发访问令牌给客户端。</p>
<h2 id="3-JWT（JSON-Web-Token）：使用、原理和源码解析"><a href="#3-JWT（JSON-Web-Token）：使用、原理和源码解析" class="headerlink" title="3. JWT（JSON Web Token）：使用、原理和源码解析"></a>3. JWT（JSON Web Token）：使用、原理和源码解析</h2><p>JWT（JSON Web Token）是一种开放标准（RFC 7519），用于在网络应用间传递安全声明。它由三个部分组成：头部（Header）、载荷（Payload）和签名（Signature）。在本篇博客中，我们将介绍JWT的基本概念、工作原理，并提供一个简单的示例代码来演示如何使用JWT进行身份验证和授权。</p>
<h3 id="3-1-JWT基本概念"><a href="#3-1-JWT基本概念" class="headerlink" title="3.1.JWT基本概念"></a>3.1.JWT基本概念</h3><ul>
<li><p><strong>头部（Header）</strong>: 头部通常由两部分组成，令牌的类型（JWT）和所使用的签名算法（例如HMAC SHA256或RSA）。</p>
</li>
<li><p><strong>载荷（Payload）</strong>: 载荷包含了一些声明（Claim），声明是关于实体（通常是用户）和其他数据的声明。有三种类型的声明：注册声明（Registered Claim）、公共声明（Public Claim）和私有声明（Private Claim）。</p>
</li>
<li><p><strong>签名（Signature）</strong>: 签名是对头部、载荷和一个密钥的组合进行加密生成的。它用于验证消息的完整性和认证发件人。</p>
</li>
</ul>
<h3 id="3-2-JWT工作原理"><a href="#3-2-JWT工作原理" class="headerlink" title="3.2.JWT工作原理"></a>3.2.JWT工作原理</h3><ol>
<li><p>用户通过提供凭据（例如用户名和密码）向服务器进行身份验证。</p>
</li>
<li><p>服务器验证用户凭据，并为用户生成JWT。</p>
</li>
<li><p>服务器将JWT作为响应返回给用户。</p>
</li>
<li><p>用户收到JWT并在后续请求中将其作为身份验证凭据发送到服务器。</p>
</li>
<li><p>服务器接收到JWT，并使用密钥验证签名和令牌的完整性。</p>
</li>
<li><p>如果JWT验证成功，服务器将对请求进行授权。</p>
</li>
</ol>
<h3 id="3-3-示例代码"><a href="#3-3-示例代码" class="headerlink" title="3.3.示例代码"></a>3.3.示例代码</h3><p>以下是一个使用Java和jjwt库实现JWT身份验证和授权的简单示例代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> io.jsonwebtoken.Claims;</span><br><span class="line"><span class="keyword">import</span> io.jsonwebtoken.Jwts;</span><br><span class="line"><span class="keyword">import</span> io.jsonwebtoken.SignatureAlgorithm;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Date;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">JwtUtil</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">SECRET_KEY</span> <span class="operator">=</span> <span class="string">&quot;my_secret_key&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String <span class="title function_">generateToken</span><span class="params">(String subject)</span> &#123;</span><br><span class="line">        <span class="type">Date</span> <span class="variable">now</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Date</span>();</span><br><span class="line">        <span class="type">Date</span> <span class="variable">expiration</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Date</span>(now.getTime() + <span class="number">3600000</span>); <span class="comment">// 1 小时</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> Jwts.builder()</span><br><span class="line">                .setSubject(subject)</span><br><span class="line">                .setIssuedAt(now)</span><br><span class="line">                .setExpiration(expiration)</span><br><span class="line">                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)</span><br><span class="line">                .compact();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String <span class="title function_">getSubjectFromToken</span><span class="params">(String token)</span> &#123;</span><br><span class="line">        <span class="type">Claims</span> <span class="variable">claims</span> <span class="operator">=</span> Jwts.parser()</span><br><span class="line">                .setSigningKey(SECRET_KEY)</span><br><span class="line">                .parseClaimsJws(token)</span><br><span class="line">                .getBody();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> claims.getSubject();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="type">boolean</span> <span class="title function_">validateToken</span><span class="params">(String token)</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>上述代码实现了JWT的生成、解析和验证功能。<code>generateToken</code>方法用于生成JWT，<code>getSubjectFromToken</code>方法用于从JWT中获取主题（用户标识），<code>validateToken</code>方法用于验证JWT的有效性。</p>
<h2 id="4-Spring-Security-OAuth2-JWT-Redis：构建安全的身份认证与授权解决方案集成"><a href="#4-Spring-Security-OAuth2-JWT-Redis：构建安全的身份认证与授权解决方案集成" class="headerlink" title="4.Spring Security + OAuth2 + JWT + Redis：构建安全的身份认证与授权解决方案集成"></a>4.Spring Security + OAuth2 + JWT + Redis：构建安全的身份认证与授权解决方案集成</h2><h3 id="4-1-添依赖"><a href="#4-1-添依赖" class="headerlink" title="4.1 添依赖"></a>4.1 添依赖</h3><p>首先，确保您的项目中包含以下依赖项：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- Spring Security --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-security<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- Spring Security OAuth2 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-oauth2-client<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- Spring Security JWT --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>io.jsonwebtoken<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>jjwt-api<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>0.10.4<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>io.jsonwebtoken<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>jjwt-impl<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>0.10.4<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">scope</span>&gt;</span>runtime<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>io.jsonwebtoken<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>jjwt-jackson<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>0.10.4<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">scope</span>&gt;</span>runtime<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- Spring Data Redis --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-data-redis<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="4-2-配置Spring-Security和OAuth2"><a href="#4-2-配置Spring-Security和OAuth2" class="headerlink" title="4.2 配置Spring Security和OAuth2"></a>4.2 配置Spring Security和OAuth2</h3><p>创建一个配置类，用于配置Spring Security和OAuth2：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@EnableWebSecurity</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SecurityConfig</span> <span class="keyword">extends</span> <span class="title class_">WebSecurityConfigurerAdapter</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> CustomUserDetailsService userDetailsService;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(HttpSecurity http)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        http</span><br><span class="line">            .authorizeRequests()</span><br><span class="line">                .antMatchers(<span class="string">&quot;/public&quot;</span>).permitAll()</span><br><span class="line">                .anyRequest().authenticated()</span><br><span class="line">                .and()</span><br><span class="line">            .oauth2Login()</span><br><span class="line">                .userInfoEndpoint()</span><br><span class="line">                    .userService(customOAuth2UserService())</span><br><span class="line">                    .and()</span><br><span class="line">                .and()</span><br><span class="line">            .csrf().disable();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> CustomOAuth2UserService <span class="title function_">customOAuth2UserService</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">CustomOAuth2UserService</span>(userDetailsService);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> PasswordEncoder <span class="title function_">passwordEncoder</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">BCryptPasswordEncoder</span>();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(AuthenticationManagerBuilder auth)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="4-3-自定义UserDetailsService"><a href="#4-3-自定义UserDetailsService" class="headerlink" title="4.3 自定义UserDetailsService"></a>4.3 自定义UserDetailsService</h3><p>创建一个自定义的<code>UserDetailsService</code>实现类，用于加载用户信息：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">CustomUserDetailsService</span> <span class="keyword">implements</span> <span class="title class_">UserDetailsService</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserRepository userRepository;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> UserDetails <span class="title function_">loadUserByUsername</span><span class="params">(String username)</span> <span class="keyword">throws</span> UsernameNotFoundException &#123;</span><br><span class="line">        <span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> userRepository.findByUsername(username);</span><br><span class="line">        <span class="keyword">if</span> (user == <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">UsernameNotFoundException</span>(<span class="string">&quot;User not found&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">org</span>.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), Collections.emptyList());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="4-4自定义OAuth2用户服务"><a href="#4-4自定义OAuth2用户服务" class="headerlink" title="4.4自定义OAuth2用户服务"></a>4.4自定义OAuth2用户服务</h3><p>创建一个自定义的<code>OAuth2UserService</code>实现类，用于处理OAuth2身份验证和加载用户信息：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">CustomOAuth2UserService</span> <span class="keyword">extends</span> <span class="title class_">DefaultOAuth2UserService</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> CustomUserDetailsService userDetailsService;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">CustomOAuth2UserService</span><span class="params">(CustomUserDetailsService userDetailsService)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.userDetailsService = userDetailsService;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> OAuth2User <span class="title function_">loadUser</span><span class="params">(OAuth2UserRequest userRequest)</span> <span class="keyword">throws</span> OAuth2AuthenticationException &#123;</span><br><span class="line">        <span class="type">OAuth2User</span> <span class="variable">oauth2User</span> <span class="operator">=</span> <span class="built_in">super</span>.loadUser(userRequest);</span><br><span class="line">        <span class="comment">// 可以在此处根据需要处理OAuth2用户信息</span></span><br><span class="line">        <span class="keyword">return</span> oauth2User;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> OAuth2User <span class="title function_">loadUser</span><span class="params">(OAuth2UserRequest userRequest, OAuth2AccessToken accessToken)</span> <span class="keyword">throws</span> OAuth2AuthenticationException &#123;</span><br><span class="line">        <span class="type">OAuth2User</span> <span class="variable">oauth2User</span> <span class="operator">=</span> <span class="built_in">super</span>.loadUser(userRequest, accessToken);</span><br><span class="line">        <span class="comment">// 可以在此处根据需要处理OAuth2用户信息和访问令牌</span></span><br><span class="line">        <span class="keyword">return</span> oauth2User;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="4-5JWT工具类"><a href="#4-5JWT工具类" class="headerlink" title="4.5JWT工具类"></a>4.5JWT工具类</h3><p>创建一个JWT工具类，用于生成和解析JWT：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> io.jsonwebtoken.Claims;</span><br><span class="line"><span class="keyword">import</span> io.jsonwebtoken.Jwts;</span><br><span class="line"><span class="keyword">import</span> io.jsonwebtoken.SignatureAlgorithm;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Value;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Date;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">JwtUtil</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Value(&quot;$&#123;jwt.secret&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String secret;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Value(&quot;$&#123;jwt.expiration&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> expiration;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">generateToken</span><span class="params">(String username)</span> &#123;</span><br><span class="line">        <span class="type">Date</span> <span class="variable">now</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Date</span>();</span><br><span class="line">        <span class="type">Date</span> <span class="variable">expiryDate</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Date</span>(now.getTime() + expiration * <span class="number">1000</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> Jwts.builder()</span><br><span class="line">                .setSubject(username)</span><br><span class="line">                .setIssuedAt(now)</span><br><span class="line">                .setExpiration(expiryDate)</span><br><span class="line">                .signWith(SignatureAlgorithm.HS512, secret)</span><br><span class="line">                .compact();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getUsernameFromToken</span><span class="params">(String token)</span> &#123;</span><br><span class="line">        <span class="type">Claims</span> <span class="variable">claims</span> <span class="operator">=</span> Jwts.parser()</span><br><span class="line">                .setSigningKey(secret)</span><br><span class="line">                .parseClaimsJws(token)</span><br><span class="line">                .getBody();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> claims.getSubject();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">boolean</span> <span class="title function_">validateToken</span><span class="params">(String token)</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Jwts.parser().setSigningKey(secret).parseClaimsJws(token);</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="4-6-Redis配置"><a href="#4-6-Redis配置" class="headerlink" title="4.6 Redis配置"></a>4.6 Redis配置</h3><p>在<code>application.properties</code>或<code>application.yml</code>中添加Redis配置：</p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring.redis.host</span>=<span class="string">localhost</span></span><br><span class="line"><span class="attr">spring.redis.port</span>=<span class="string">6379</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="4-7Redis存储访问令牌"><a href="#4-7Redis存储访问令牌" class="headerlink" title="4.7Redis存储访问令牌"></a>4.7Redis存储访问令牌</h3><p>使用Redis存储访问令牌的代码示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.redis.core.RedisTemplate;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeUnit;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TokenStore</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> RedisTemplate&lt;String, String&gt; redisTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">TokenStore</span><span class="params">(RedisTemplate&lt;String, String&gt; redisTemplate)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.redisTemplate = redisTemplate;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">storeToken</span><span class="params">(String key, String token, <span class="type">long</span> expiration)</span> &#123;</span><br><span class="line">        redisTemplate.opsForValue().set(key, token, expiration, TimeUnit.SECONDS);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getToken</span><span class="params">(String key)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> redisTemplate.opsForValue().get(key);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">deleteToken</span><span class="params">(String key)</span> &#123;</span><br><span class="line">        redisTemplate.delete(key);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>总结：</p>
<p>通过以上的配置和代码示例，我们可以实现基于Spring Security、OAuth2、JWT和Redis的安全身份认证和授权功能。</p>
<p>希望本篇博客能够帮助你对Spring Security + OAuth2 + JWT + Redis的功能和原理有一个更深入的了解，并为你构建安全可靠的身份认证和授权解决方案提供有力的支持！</p>
<p>以上就是关于Spring Security + OAuth2 + JWT + Redis的功能和原理的介绍以及代码示例。希望你喜欢并从中受益！</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://hkl.gitee.io/houkl">Houkl</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://hkl.gitee.io/houkl/2018/08/16/srping/SpringSecurityOAuth2JWTRedis/">http://hkl.gitee.io/houkl/2018/08/16/srping/SpringSecurityOAuth2JWTRedis/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://hkl.gitee.io/houkl" target="_blank">坤个人博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://s1.ax1x.com/2023/06/05/pCCUheP.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/houkl/2018/09/12/srping/springCloud/" title="入门指南：使用Spring Cloud构建分布式微服务架构"><img class="cover" src="https://s1.ax1x.com/2023/06/06/pCP5niD.png" onerror="onerror=null;src='/houkl/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">入门指南：使用Spring Cloud构建分布式微服务架构</div></div></a></div><div class="next-post pull-right"><a href="/houkl/2018/07/21/system/linuxGrammar/" title="Linux 一些基本语法记录"><img class="cover" src="https://s1.ax1x.com/2023/06/06/pCPWe3R.png" onerror="onerror=null;src='/houkl/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Linux 一些基本语法记录</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://s1.ax1x.com/2023/05/31/p9v6spQ.md.jpg" onerror="this.onerror=null;this.src='/houkl/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Houkl</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/houkl/archives/"><div class="headline">文章</div><div class="length-num">21</div></a><a href="/houkl/tags/"><div class="headline">标签</div><div class="length-num">0</div></a><a href="/houkl/categories/"><div class="headline">分类</div><div class="length-num">8</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/houkunliang"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">个人博客不定期更新，还望各位看官谅解</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E5%8A%9F%E8%83%BD%E4%BB%8B%E7%BB%8D-Spring-Security%EF%BC%9A"><span class="toc-number">1.</span> <span class="toc-text">1. 功能介绍 Spring Security：</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-%E7%A4%BA%E4%BE%8B%E4%BB%A3%E7%A0%81-%E7%8E%B0%E5%9C%A8%EF%BC%8C%E8%AE%A9%E6%88%91%E4%BB%AC%E9%80%9A%E8%BF%87%E4%B8%80%E4%B8%AA%E7%AE%80%E5%8D%95%E7%9A%84%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B%E6%9D%A5%E6%BC%94%E7%A4%BASpring-Security%E7%9A%84%E4%BD%BF%E7%94%A8%EF%BC%9A"><span class="toc-number">1.1.</span> <span class="toc-text">2.1. 示例代码 现在，让我们通过一个简单的代码示例来演示Spring Security的使用：</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-OAuth2%EF%BC%9A%E4%BD%BF%E7%94%A8%E3%80%81%E5%8E%9F%E7%90%86"><span class="toc-number">2.</span> <span class="toc-text">2.OAuth2：使用、原理</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-OAuth2%E5%9F%BA%E6%9C%AC%E6%A6%82%E5%BF%B5"><span class="toc-number">2.1.</span> <span class="toc-text">2.1.OAuth2基本概念</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-OAuth2-%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86"><span class="toc-number">2.2.</span> <span class="toc-text">2.2. OAuth2 工作原理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-OAuth2%E7%A4%BA%E4%BE%8B%E4%BB%A3%E7%A0%81"><span class="toc-number">2.3.</span> <span class="toc-text">2.3. OAuth2示例代码</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-JWT%EF%BC%88JSON-Web-Token%EF%BC%89%EF%BC%9A%E4%BD%BF%E7%94%A8%E3%80%81%E5%8E%9F%E7%90%86%E5%92%8C%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90"><span class="toc-number">3.</span> <span class="toc-text">3. JWT（JSON Web Token）：使用、原理和源码解析</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-JWT%E5%9F%BA%E6%9C%AC%E6%A6%82%E5%BF%B5"><span class="toc-number">3.1.</span> <span class="toc-text">3.1.JWT基本概念</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-JWT%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86"><span class="toc-number">3.2.</span> <span class="toc-text">3.2.JWT工作原理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-3-%E7%A4%BA%E4%BE%8B%E4%BB%A3%E7%A0%81"><span class="toc-number">3.3.</span> <span class="toc-text">3.3.示例代码</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-Spring-Security-OAuth2-JWT-Redis%EF%BC%9A%E6%9E%84%E5%BB%BA%E5%AE%89%E5%85%A8%E7%9A%84%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81%E4%B8%8E%E6%8E%88%E6%9D%83%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88%E9%9B%86%E6%88%90"><span class="toc-number">4.</span> <span class="toc-text">4.Spring Security + OAuth2 + JWT + Redis：构建安全的身份认证与授权解决方案集成</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-%E6%B7%BB%E4%BE%9D%E8%B5%96"><span class="toc-number">4.1.</span> <span class="toc-text">4.1 添依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2-%E9%85%8D%E7%BD%AESpring-Security%E5%92%8COAuth2"><span class="toc-number">4.2.</span> <span class="toc-text">4.2 配置Spring Security和OAuth2</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3-%E8%87%AA%E5%AE%9A%E4%B9%89UserDetailsService"><span class="toc-number">4.3.</span> <span class="toc-text">4.3 自定义UserDetailsService</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-4%E8%87%AA%E5%AE%9A%E4%B9%89OAuth2%E7%94%A8%E6%88%B7%E6%9C%8D%E5%8A%A1"><span class="toc-number">4.4.</span> <span class="toc-text">4.4自定义OAuth2用户服务</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-5JWT%E5%B7%A5%E5%85%B7%E7%B1%BB"><span class="toc-number">4.5.</span> <span class="toc-text">4.5JWT工具类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-6-Redis%E9%85%8D%E7%BD%AE"><span class="toc-number">4.6.</span> <span class="toc-text">4.6 Redis配置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-7Redis%E5%AD%98%E5%82%A8%E8%AE%BF%E9%97%AE%E4%BB%A4%E7%89%8C"><span class="toc-number">4.7.</span> <span class="toc-text">4.7Redis存储访问令牌</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/houkl/2019/06/28/java/volatile/" title="深入理解Java中的volatile关键字"><img src="https://s1.ax1x.com/2023/06/06/pCiS2tJ.png" onerror="this.onerror=null;this.src='/houkl/img/404.jpg'" alt="深入理解Java中的volatile关键字"/></a><div class="content"><a class="title" href="/houkl/2019/06/28/java/volatile/" title="深入理解Java中的volatile关键字">深入理解Java中的volatile关键字</a><time datetime="2019-06-27T16:00:00.000Z" title="发表于 2019-06-28 00:00:00">2019-06-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/houkl/2019/04/03/java/reentrantLock/" title="深入探索Java中的ReentrantLock"><img src="https://s1.ax1x.com/2023/06/06/pCiSafs.png" onerror="this.onerror=null;this.src='/houkl/img/404.jpg'" alt="深入探索Java中的ReentrantLock"/></a><div class="content"><a class="title" href="/houkl/2019/04/03/java/reentrantLock/" title="深入探索Java中的ReentrantLock">深入探索Java中的ReentrantLock</a><time datetime="2019-04-02T16:00:00.000Z" title="发表于 2019-04-03 00:00:00">2019-04-03</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/houkl/2019/01/26/java/rushToPurchase/" title="用Redis + Lua 实现商品抢购"><img src="https://s1.ax1x.com/2023/06/06/pCiSgk4.png" onerror="this.onerror=null;this.src='/houkl/img/404.jpg'" alt="用Redis + Lua 实现商品抢购"/></a><div class="content"><a class="title" href="/houkl/2019/01/26/java/rushToPurchase/" title="用Redis + Lua 实现商品抢购">用Redis + Lua 实现商品抢购</a><time datetime="2019-01-25T16:00:00.000Z" title="发表于 2019-01-26 00:00:00">2019-01-26</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/houkl/2018/12/15/java/synchronized/" title="深入了解 Java 中的 Synchronized 关键字"><img src="https://s1.ax1x.com/2023/06/06/pCPzDde.png" onerror="this.onerror=null;this.src='/houkl/img/404.jpg'" alt="深入了解 Java 中的 Synchronized 关键字"/></a><div class="content"><a class="title" href="/houkl/2018/12/15/java/synchronized/" title="深入了解 Java 中的 Synchronized 关键字">深入了解 Java 中的 Synchronized 关键字</a><time datetime="2018-12-14T16:00:00.000Z" title="发表于 2018-12-15 00:00:00">2018-12-15</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/houkl/2018/11/05/middleware/activeMQ/" title="ActiveMQ初见"><img src="https://s1.ax1x.com/2023/06/06/pCPxUHg.png" onerror="this.onerror=null;this.src='/houkl/img/404.jpg'" alt="ActiveMQ初见"/></a><div class="content"><a class="title" href="/houkl/2018/11/05/middleware/activeMQ/" title="ActiveMQ初见">ActiveMQ初见</a><time datetime="2018-11-04T16:00:00.000Z" title="发表于 2018-11-05 00:00:00">2018-11-05</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By Houkl</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/houkl/js/utils.js"></script><script src="/houkl/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><div class="js-pjax"></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="false"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div class="no-result" id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/houkl/js/search/local-search.js"></script></div></div></body></html>